package com.ruoyi.common.utils;

import java.security.SecureRandom;

public class PasswordGenerator {

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String SYMBOLS = "-_";

    public static String generatePassword() {
        StringBuilder password = new StringBuilder();

        // 添加一个大小写字母
        password.append(generateRandomCharacter(CHARACTERS));

        // 添加一个数字
        password.append(generateRandomCharacter(DIGITS));

        // 添加一个符号
        password.append(generateRandomCharacter(SYMBOLS));

        // 生成其余字符
        SecureRandom random = new SecureRandom();
        int remainingLength = random.nextInt(19) + 5; // 生成5到23之间的随机数
        while (remainingLength > 0) {
            String characters = CHARACTERS + DIGITS + SYMBOLS;
            password.append(generateRandomCharacter(characters));
            remainingLength--;
        }

        // 打乱密码中的字符顺序
        String shuffledPassword = shufflePassword(password.toString());

        return shuffledPassword;
    }

    private static char generateRandomCharacter(String characters) {
        SecureRandom random = new SecureRandom();
        int index = random.nextInt(characters.length());
        return characters.charAt(index);
    }

    private static String shufflePassword(String password) {
        char[] charArray = password.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            int randomIndex = (int) (Math.random() * charArray.length);
            char temp = charArray[i];
            charArray[i] = charArray[randomIndex];
            charArray[randomIndex] = temp;
        }
        return new String(charArray);
    }

    public static void main(String[] args) {
        String password = generatePassword();
        System.out.println(password);
    }

}
